<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";
import { formatDate } from "@/utils";
import { nextTick , onMounted} from "vue";

const { pageData, agrMap } = useData();
import { deleteData, getDataByPage, ifaceDmzSetOuter, ifaceDmzSetIp } from "@/api/modules/control-strategy/host-manage";
import UpdateForm from "./components/UpdateForm/index.vue";

const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);
const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {
    ipproto: "0"
  },
  responseKey: {
    list: "data",
    total: "total"
  }
});

function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      mac: formData.mac,
      ip: formData.ip,
      ifid: formData.ifid
    }
  });
}

onMounted(async ()=>{
  await getLinks();
  loadDataCb();
})

async function reloadDataCb() {
  reloadData();
  await getLinks();
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      mac: formData.mac,
      ip: formData.ip,
      ifid: formData.ifid
    }
  });
}

/**删除*/
import useDelete from "@/hooks/useDelete";
import { computed, ref } from "vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import { ifaceLinks } from "@/api/modules/common";
import { ElMessage } from "element-plus";
import { ifaceAttrGet } from "@/api/modules/dynamic-camouflage/line-config";

const { deleteHandler, idList } = useDelete();

async function deleteCb(id) {
  await deleteHandler({
    api: deleteData,
    multiple: false,
    sendData: {
      id: [id]
    },
    hideMessageBox: false
  });
  loadDataCb();
}

function selectCb(data) {
  console.log(data);
  idList.value = data.rowList.map(item => item.userId);
}

const links = ref([]);
const wanIfid = ref([]);
const lanIfid = ref([]);

async function getLinks() {
  const res = await ifaceLinks();
  console.log("==========", res);
  let arr = [];
  for (const link of res) {
    if (link.linkmode.includes("动态网络")) {
      let attr = link.ifid.split("-");
      let attrNames = link.ifname.split("-");
      let attrNameTwo = attrNames[0].split(":");
      arr.push({
        ifid: attr[0],
        linkid: link.linkid,
        name: `线路${link.linkid}-LAN`,
        ifname: attrNameTwo[1],

        label:`线路${link.linkid}`
      });
      lanIfid.value.push(attr[0]);
      arr.push({
        ifid: attr[1],
        linkid: link.linkid,
        name: `线路${link.linkid}-WAN`,
        ifname: attrNames[1],
        label:`线路${link.linkid}`
      });
      wanIfid.value.push(attr[1]);
    } else {
      let attrNames = link.ifname.split(":");
      arr.push({
        ...link,
        name: `线路${link.linkid}`,
        ifname: attrNames[1],

        label:`线路${link.linkid}`
      });
    }
  }
  links.value = arr.filter(item => item.name.includes("LAN"));
  console.log("  links.value ", links.value);
  if (arr?.length) {
    formData.ifid = links.value[0].ifid;
    formData.ifname = links.value[0].ifname;

    ifaceAttrGetCb();
  }
}

function selectLoad() {}

getLinks();

// 隔离与未隔离
async function setIsOuter(data) {
  const res = await ifaceDmzSetOuter({
    is_outer: data.row.is_outer == "1" ? "0" : "1",
    id: data.row.id,
    ifid: formData.ifid
  });
  ElMessage.success("更新成功");
  loadDataCb();
}

const editInput = ref("");
const editIndex = ref(null);
const editInputRef = ref(null);
const selectList = ref([]);

function cidrToIpList(cidr) {
  const [ip, mask] = cidr.split("/");
  const ipParts = ip.split(".").map(Number);
  const maskBits = parseInt(mask, 10);
  const start = (ipParts[0] << 24) | (ipParts[1] << 16) | (ipParts[2] << 8) | ipParts[3];
  const end = start | ((1 << (32 - maskBits)) - 1);

  const ipList = [];
  for (let i = start; i <= end; i++) {
    ipList.push([(i >>> 24) & 255, (i >>> 16) & 255, (i >>> 8) & 255, i & 255].join("."));
  }
  return ipList;
}

async function ifaceAttrGetCb() {
  const res = await ifaceAttrGet({
    ifid: formData.ifid
  });
  if (res.vdyn && res.vdyn.includes("/24")) {
    let list = cidrToIpList(res.vdyn);
    // list = list.filter(item => !this.hasOuteripList.includes(item));
    selectList.value = list;
  }
}

function changeEditIndex(index) {
  try {
    editIndex.value = index;
    console.log("tableData.list[index]", index);
    editInput.value = tableData.list[index]?.outerip || "";
    setTimeout(() => {
      nextTick(() => {
        // 选择框自动展开
        editInputRef.value.toggleMenu();
      });
    }, 500);
  } catch (e) {
    console.log(e);
  }
}

async function visibleChange(state) {
  console.log(state);
  console.log(editInput.value);
  if (!state) {
    if (editInput.value === tableData.list[editIndex.value]?.outerip) {
      editIndex.value = -1;
      return;
    }
    try {
      await ifaceDmzSetIp({
        outerip: editInput.value,
        id: tableData.list[editIndex.value]?.id,
        ifid: formData.ifid
      });
      ElMessage.success("更新成功");
      loadDataCb();
      editIndex.value = -1;
      return;
    } catch (e) {
      editIndex.value = -1;
    }
  }
}
</script>

<template>
  <BaseUpDown>
    <template #up>
      <BaseCollapse title="主机管控">
        <template #header>
          <div class="h-box justify-end" style="width: 150px; float: right" @click.stop></div>
        </template>
        <el-form>
          <div class="h-box" style="flex-wrap: wrap">
            <el-form-item label="MAC">
              <el-input v-model="formData.mac" placeholder="请输入" style="width: 120px" />
            </el-form-item>
            <el-form-item class="mg-l-sm" label="IP">
              <el-input v-model="formData.ip" placeholder="请输入" style="width: 120px" />
            </el-form-item>
            <el-form-item class="mg-l-sm" label="网口">
              <el-select @change="selectLoad" style="width: 140px" v-model="formData.ifid">
                <el-option v-for="item in links" :key="item.ifid" :value="item.ifid" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <BaseButton class="mg-l-sm" style="margin-bottom: 18px" @click="loadDataCb()" type="search_icon_text" />
            <BaseButton class="mg-l-sm" style="margin-bottom: 18px" @click="reloadDataCb()" type="reset_icon_text" />
          </div>
        </el-form>
      </BaseCollapse>
    </template>
    <he-table
      @handle-current-change="loadDataCb"
      :total="tableData.total"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="false"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="true"
      @select="selectCb"
    >
      <template #1Default="{ data }">
        {{ formData?.ifname }}
      </template>
      <template #outeripDefault="{ data }">
        <el-select
          @visible-change="visibleChange"
          autofocus
          v-if="editIndex === data.$index"
          placeholder="请选择"
          v-model="editInput"
          type="text"
          ref="editInputRef"
        >
          <el-option v-for="item in selectList" :key="item" :value="item" :label="item" />
        </el-select>
        <span @click="changeEditIndex(data.$index)" v-else class="h-box align-items-center justify-center cursor-pointer">
          {{ data.row.outerip }}
          <el-icon class="mg-l-sm"><Edit /></el-icon>
        </span>
      </template>
      <template #is_outerDefault="{ data }">
        {{ data.row.is_outer == "1" ? "连通" : "隔离" }}
      </template>
      <template #operationDefault="{ data }">
        <base-button @click="setIsOuter(data)" v-if="!(data.row.is_outer == '1')" type="connect_icon_text"></base-button>
        <base-button @click="setIsOuter(data)" v-else type="disabled_icon_text"></base-button>
      </template>
    </he-table>
  </BaseUpDown>
</template>
